<template>
  <page-wrap
    stay-still
    back
    hide-tab
    :title="dynamicTitle"
    contentWrapColor="#fff"
  >
    <view class="form-wrap" :style="'margin-bottom:' + inputBottom + 'px;'">
      <view class="form-top">
        <view class="form-top-title"
          >{{ trainId ? '编辑' : '添加' }}校园经历</view
        >
        <view class="form-top-subtitle"
          >{{ trainId ? '编辑' : '添加' }}校园经历，让招聘者更了解你</view
        >
      </view>
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view
            class="form-item-wrap"
            @click.capture="handleSelect($event, item, index)"
          >
            <u-form-item
              :class="[{ pick: item.comp }, { multiple: item.multiple }]"
              :label="item.label"
              :prop="item.prop"
              :border-bottom="!item.hideBorderBottom"
              :required="item.required"
            >
              <!-- textarea -->
              <u-input
                v-if="!item.comp && item.type === 'textarea'"
                :class="[
                  'form-input',
                  { textarea: item.inputType === 'textarea' }
                ]"
                v-model="form[item.prop]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder"
                :type="item.inputType"
                :height="item.height"
                :maxlength="item.maxlength || 150"
                :clearable="false"
                :id="item.prop"
                @click="handleTextAreaClick(item)"
                disabled
              />
              <u-input
                v-else
                :class="[
                  'form-input',
                  { textarea: item.inputType === 'textarea' }
                ]"
                v-model="form[item.prop]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder"
                :type="item.inputType"
                :height="item.height"
                :maxlength="item.maxlength || 150"
                :clearable="false"
                :id="item.prop"
              />
              <text v-if="item.multiple">~</text>
              <u-input
                v-if="item.multiple"
                class="form-input"
                v-model="form[item.prop2]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder2"
                :clearable="false"
                @click="handleMultipleSelect(item)"
                :id="item.prop2"
              />

              <!-- 下拉选择 -->
              <u-select
                class="form-select"
                v-model="item.show"
                :list="item.data"
                v-if="item.comp === 'select'"
                @confirm="handleConfirm($event, item)"
              ></u-select>
              <!-- 时间选择 -->
              <u-picker
                class="form-time"
                mode="time"
                v-model="item.show"
                :params="item.param"
                :start-year="item.start"
                :end-year="item.end"
                :default-time="form[tapTarget]"
                v-if="item.comp === 'time'"
                @confirm="handleConfirm($event, item)"
              ></u-picker>
            </u-form-item>
          </view>
        </block>
      </u-form>
    </view>

    <view class="page-action">
      <view class="btn-delete" v-if="trainId">
        <u-button
          :hair-line="false"
          :plain="true"
          :custom-style="btnSaveStyle"
          @click="handleDelete"
          >删除</u-button
        >
      </view>
      <view class="btn-save">
        <u-button type="primary" :custom-style="btnStyle" @click="handleSave"
          >保存</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import {
  addPersonStudentLeader,
  updatePersonStudentLeader,
  deletePersonStudentLeaderDetail,
  getResumeData
} from '@/api/index';
import { formatTime } from '@/utils/handle';
import MyTextarea from '../components/MyTextarea.vue';
import ShareMixin from '@/mixins/share';
import newResumeItem from '@/mixins/newResumeItem';
import { dealSingleModuleScore } from '@/api/modules/career.js';
import { throttle } from 'lodash';

export default {
  mixins: [ShareMixin, newResumeItem],
  components: {
    MyTextarea
  },
  data() {
    return {
      inputBottom: 0,
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      trainId: null,
      info: {},
      form: {
        schoolOrgName: '',
        schoolOrgPositionName: '',
        schoolExp_startdate: '',
        schoolExp_enddate: '',
        schoolExp_desc: ''
      },
      formList: [
        {
          label: '校园组织名称',
          prop: 'schoolOrgName',
          inputPlaceholder: '必填',
          maxlength: '20',
          required: true
        },
        // {
        //   label: "担任角色",
        //   prop: "schoolOrgPositionName",
        //   inputPlaceholder: "必填",
        // },
        {
          label: '起止时间',
          multiple: true,
          prop: 'schoolExp_startdate',
          prop2: 'schoolExp_enddate',
          inputPlaceholder: '开始时间',
          inputPlaceholder2: '结束时间',
          comp: 'time',
          show: false,
          setProp2: false,
          param: {
            year: true,
            month: true,
            day: true,
            hour: false,
            minute: false,
            second: false
          },
          start: new Date().getFullYear() - 70,
          end: new Date().getFullYear() + 4,
          required: true
        },
        {
          label: '校园经历描述',
          prop: 'schoolExp_desc',
          type: 'textarea',
          inputPlaceholder: '简要对校园经历进行描述，如工作内容或职责',
          // height: "260",
          maxlength: 1000,
          showWords: true
          // hideBorderBottom: true,
        }
      ],
      modelVisible: false,
      btnSaveStyle: {
        border: 'none',
        backgroundColor: '#E9ECEF'
      },
      btnStyle: {
        border: 'none'
      },
      rules: {
        schoolOrgName: [
          {
            required: true,
            message: '请输入校园组织名称'
          },
          {
            max: 20,
            message: '名称长度不超过20字符'
          }
        ],
        // schoolOrgPositionName: [
        //   {
        //     required: true,
        //     message: "请输入担任角色",
        //   },
        // ],
        schoolExp_startdate: [
          {
            validator: this.testStartDate
          }
        ]
      },
      tapTarget: ''
    };
  },
  watch: {
    info: {
      handler(val) {
        if (val.studentLeaderArr) {
          let arr = JSON.parse(
            JSON.stringify(
              val.studentLeaderArr.find(
                (ele) => ele.person_studengLeaderId == this.trainId
              )
            )
          );

          this.form.schoolOrgName = arr.person_studentLeaderjob;
          this.form.schoolExp_enddate = arr.person_studentLeaderstopdate;
          this.form.schoolExp_startdate = arr.person_studentLeaderstartdate;
          // this.form.schoolOrgPositionName = "暂无岗位";
          this.form.schoolExp_desc = arr.person_studentLeaderjobdesc;
        }
      },
      deep: true,
      immediate: true
    },
    inputBottom(val) {
      if (val) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 99999,
            duration: 0
          });
        });
      }
    }
  },
  onLoad(options) {
    if (options.id || options.person_studengLeaderId) {
      this.trainId = options.id || options.person_studengLeaderId;
      this.getResumeData();
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
    // this.setEndDateToday();
  },
  // onShareAppMessage() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },
  // onShareTimeline() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },
  onShow() {
    //读取切换页面之后输入的内容
    const newResumeCurrentFormItemInfo = uni.getStorageSync(
      'newResumeCurrentFormItemInfo'
    );
    this.$set(
      this.form,
      newResumeCurrentFormItemInfo.prop,
      newResumeCurrentFormItemInfo.value
    );
    uni.removeStorageSync('newResumeCurrentFormItemInfo');
  },
  methods: {
    //编辑单个简历模块上报
    dealSingleModuleScore() {
      const params = {
        personId: this.personId || uni.getStorageSync('person-id').slice(2),
        resumeModule: 11 //简历模块 1:基本信息 2:求职状态 3:求职意向 4:工作经历 5:项目经验 6：自我评价 7：教育背景 8：个人证书 9：技能特长 10：培训经历 11：校园经历 12：奖项荣誉
      };
      dealSingleModuleScore(params);
    },
    handleTextAreaClick(item) {
      uni.setStorageSync('newResumeCurrentFormItemInfo', {
        ...item,
        value: this.form[item.prop]
      });
      if (item.type == 'textarea') {
        uni.navigateTo({
          url: `/pagesSub/newResume/generalTextAreaPage/index`
        });
      }
    },
    setEndDateToday() {
      this.form.schoolExp_enddate = formatTime(new Date(), 'yyyy-MM-dd');
      this.form.schoolExp_startdate = formatTime(new Date(), 'yyyy-MM-dd');
    },
    testStartDate(rule, value, callback) {
      if (!value) {
        return callback('请选择开始时间');
      } else if (!this.form.schoolExp_enddate) {
        return callback('请选择结束时间');
      } else if (value >= this.form.schoolExp_enddate) {
        return callback('起止时间有误');
      }
      return true;
    },
    handleBottom(e) {
      this.inputBottom = e > 130 ? e - 130 : 0;
    },
    handleClear(e, item) {
      this.$set(this.form, item.prop, e);
    },
    getResumeData() {
      if (
        !getApp().globalData.resumeInfo ||
        !getApp().globalData.resumeInfo.Iname_p
      ) {
        uni.showLoading();
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1
          })
        };
        getResumeData(param)
          .then((res) => {
            this.info = res.data;
          })
          .finally(() => {
            uni.hideLoading();
          });
      } else {
        console.log(
          'getApp().globalData.resumeInfo)',
          getApp().globalData.resumeInfo
        );
        this.info = JSON.parse(JSON.stringify(getApp().globalData.resumeInfo));
      }
    },

    handleSave: throttle(function () {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.saveTrain();
        }
      });
    }, 5000),

    // 添加/修改
    saveTrain() {
      let list = this.form;
      if (
        list.schoolExp_startdate > list.schoolExp_enddate ||
        list.schoolExp_startdate > formatTime(new Date(), 'yyyy-MM-dd') ||
        list.schoolExp_enddate > formatTime(new Date(), 'yyyy-MM-dd')
      ) {
        return uni.showToast({ icon: 'none', title: '起止时间有误' });
      }

      let params = {
        personId: this.personId,
        startDate: list.schoolExp_startdate,
        endDate: list.schoolExp_enddate,
        bToNow: 0,
        leaderName: list.schoolOrgName,
        des: list.schoolExp_desc
      };
      // let listRest = { schoolExp_startdate, schoolExp_enddate };
      // let dataArr = {
      //   startDate: list.schoolExp_startdate + "-01",
      //   endDate: list.schoolExp_enddate + "-01",
      //   leaderName: list.schoolOrgName,
      //   des: list.schoolExp_desc,
      // };
      let fcn = addPersonStudentLeader;
      let successTxt = '添加成功';
      if (this.trainId) {
        fcn = updatePersonStudentLeader;
        successTxt = '修改成功';
        params = { leaderId: this.trainId, ...params };
        // params.updateArr = JSON.stringify(dataArr);
      }
      // else {
      //   params.insertArr = JSON.stringify(dataArr);
      // }
      fcn(params)
        .then((res) => {
          if (res.code == 200) {
            this.dealSingleModuleScore();
            uni.setStorageSync('resumeUpdated', true); //设置一个标识，在resumeAssesment如果为true才会请求接口
            uni.showToast({
              icon: 'none',
              title: successTxt,
              complete() {
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              }
            });
          } else {
            uni.showToast({ icon: 'none', title: res.status_desc });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDelete() {
      uni.showModal({
        title: '温馨提示',
        content: `确认删除校园经历？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            let params = {
              array: JSON.stringify({
                personId: this.personId,
                person_studengLeaderId: this.trainId
              })
            };
            deletePersonStudentLeaderDetail(params)
              .then((res) => {
                if (res.code == 200) {
                  this.dealSingleModuleScore();
                  uni.setStorageSync('resumeUpdated', true); //设置一个标识，在resumeAssesment如果为true才会请求接口
                  uni.showToast({
                    icon: 'none',
                    title: '删除成功',
                    complete() {
                      setTimeout(() => {
                        uni.navigateBack();
                      }, 1500);
                    }
                  });
                } else {
                  uni.showToast({ icon: 'none', title: res.status_desc });
                }
              })
              .catch((err) => {
                console.error(err);
              });
          }
        }
      });
    },
    handleSelect($event, item, index) {
      if (item.comp) {
        this.$set(item, 'show', true);
        this.tapTarget = $event.target.id;
      }
    },
    handleMultipleSelect(item) {
      if (item.multiple) {
        this.$set(item, 'setProp2', true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        if (item.setProp2) {
          this.$set(this.form, item.prop2, time);
          this.$set(item, 'setProp2', false);
          return;
        }
        this.$set(this.form, item.prop, time);
        console.log('this.form, item.prop, time', this.form, item.prop, time);
      }
    }
  }
};
</script>

<style lang="scss">
$img-base-resume: $img-base + 'resume/';
.form-wrap {
  flex-grow: 1;
  padding: 32rpx 28rpx 175rpx 32rpx;
  background-color: $uni-bg-color;
  border-radius: $uni-border-radius-big;
  .form-top {
    margin-bottom: 74rpx;
    &-title {
      font-size: 48rpx;
      color: #000000;
      font-weight: bold;
      margin-bottom: 16rpx;
    }
    &-subtitle {
      font-size: 26rpx;
      color: #555555;
    }
  }
  ::v-deep .u-form {
    padding-top: 0;
    // margin: 32rpx 32rpx 0;

    .form-text {
      display: block;
      width: calc(100vw - 128rpx);
      box-sizing: border-box;
      .textarea-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
        word-break: break-all;
        textarea,
        .textarea {
          height: 460rpx !important;
          font-size: $uni-font-size-sm;
          word-break: break-all;
        }
        .placeholder {
          font-size: $uni-font-size-sm;
        }
      }
    }

    .textarea {
      background-color: #f8f9fb;
      border-radius: $uni-border-radius-big;
      .u-input {
        background-color: #f8f9fb;
        border-radius: $uni-border-radius-big;
      }
    }
    .u-input__textarea {
      padding: 24rpx 32rpx;
      font-size: $uni-font-size-nor;
    }

    .content-words {
      margin-right: 10rpx;
      text-align: right;
      color: $uni-text-color-888;
      font-size: $uni-font-size-sm;
    }

    .btn-group {
      padding: 0 24rpx;
      line-height: 102rpx;
      .cancel,
      .confirm {
        padding: 0 16rpx;
      }
    }
    .u-form-item--left__content__label {
      font-size: 28rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #555555;
      line-height: 40rpx;
    }
    .u-input__input {
      font-size: 32rpx !important;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #000000 !important;
      line-height: 44rpx;
    }
  }
}
.page-action {
  position: fixed;
  bottom: 94rpx;
  width: 100vw;
  margin: 0;
  padding: 0rpx 32rpx;
  z-index: 9;
  .btn-delete {
    flex-shrink: 0;
    width: 180rpx;
    margin-right: 40rpx;
  }
  .btn-save {
    flex-shrink: 1;
    // margin: 82rpx 0 4rpx;
    width: 100%;
    border-radius: 16rpx;
  }
}
.u-form-item {
  ::v-deep .u-form-item__body::after {
    top: 64%;
    margin-top: 0rpx;
    width: 24rpx;
    height: 24rpx;
    background-image: url($img-base + 'career/right-arrow.png?v=1');
  }
}
</style>
